/**
 * name: common
 * version: v3.0.2
 * update: ie8 opc0显示bug
 * date: 2016-08-02
 */
define(function(require, exports, module) {
    var $ = require('jquery');
    var base = require('base');

    if(base.browser.ie<8){
        alert('您的浏览器版本过低，请升级或使用chrome、Firefox等高级浏览器！');
    }

    $('body').attr('data-w',$('body').outerWidth());
    /*var throttleResize = base.throttle(function(){
        if(base.getType()!=='Pc'){
            var new_width = $('body').outerWidth();
            if(new_width !== $('body').data('w')){
                document.location.reload()
            }
        }
    });
    $(window).on('resize',function(){
        throttleResize();
    });*/

    //字号调节
    var $speech=$('.myart:visible'),
        defaultsize=parseFloat($speech.css('font-size'));
    if($speech.length){
        //window.localStorage &&  localStorage.getItem('fz') && $speech.css('font-size', localStorage.getItem('fz')+'px');
        $('body').on('click','#switcher a',function(){
            var num=parseFloat($speech.css('font-size'))
            switch(this.id){
                case'small':num/=1.4
                break
                case'big':num*=1.4
                break
                default:num=defaultsize
            }
            $speech.css('font-size',num+'px')
          //window.localStorage && localStorage.setItem('fz',num);
        })
    }

    //页面平滑滚动
    if(base.getType() == 'Pc' && base.browser.ie > 8){
        require('smoothscroll');
    }

    //图片懒加载
    require('lazyload');
    $("img").scrollLoading({
        attr:"data-url"
    });
  
    //屏蔽ie78 console未定义错误
    if (typeof console === 'undefined') {
        console = { log: function() {}, warn: function() {} }
    };

    /*
    * 常用工具
    */
    //返回顶部
    $('body').on('click','.gotop',function(){$('html,body').stop(1).animate({scrollTop:'0'},300);return false});
    //关闭当前页
    $('body').on('click','.closewin',function(){window.opener=null;window.open("","_self");window.close()});
    //打印当前页
    $('body').on('click','.print',function(){window.print()});
  
    //textarea扩展max-length
    $('textarea[max-length]').on('change blur keyup',function(){
        var _val=$(this).val(),_max=$(this).attr('max-length');
        if(_val.length>_max){
            $(this).val(_val.substr(0,_max));
        };
    });

    //延时显示
    if(base.browser.ie<9){
        $('.opc0').css('filter','unset')
    }else{
        $('.opc0').animate({'opacity':'1'},160);
    }

    // placeholder
    $('input, textarea').placeholder();

    //按需渲染
    base.scanpush();
    //响应图片
    base.resImg();



    /*------图表公用------*/
    //竖向折线图、柱状图
    var chart1 = function(id,data1,data2,chartType,chartColor,barName){
        var ec1 = module.exports.ec1= echarts.init(document.getElementById(id),'dark');  
        var notBar = false;
        if (chartType == 'line') {
            notBar = true;
        } 
        var option_second = {
            tooltip : {
                trigger: 'axis',
                axisPointer : {
                    type : 'shadow'
                }
            },
            grid: {  
                left: '3',  
                right: '20',  
                bottom: '0',  
                top:'20',
                containLabel: true  
            },
            calculable: true,  
            xAxis : [
                {
                    type : 'category',
                    axisLabel:{  
                        interval:'auto',
                        //rotate:-10

                   },
                   data : data1
                }
            ],
            yAxis: [  
                {  
                    show: true,  
                    type: 'value', 
                    splitArea: {show: true}  
                }  
            ],  
            series: [  
                {  
                    name: barName,    
                    type: chartType,
                    itemStyle: {
                        normal: {
                            color:chartColor
                        }
                    }, 
                    data: data2,
                    label: {
                        normal: {
                            show: notBar,
                            position: 'top',
                            textStyle:{
                                color:"#ffffff"
                            }
                        }
                    }
                }
            ]
        };
        ec1.setOption(option_second);
    };

    //横向柱状图
    var chart2 = function(id,data1,data2,chartType,chartColor,barName){
        var ec2 = module.exports.ec2 = echarts.init(document.getElementById(id),'dark');   
        var option_second = {
            tooltip : {
                trigger: 'axis',
                axisPointer : {
                    type : 'shadow'
                }
            },
            grid: {  
                left: 10,  
                right: '20',  
                bottom: '0',  
                top:'20',
                containLabel: true  
            },
            calculable: true,  
            yAxis : [
                {
                    type : 'category',
                    axisLabel:{  
                        interval:'auto',
                        //rotate:-10

                   },
                   data : data1
                }
            ],
            xAxis: [  
                {  
                    show: true,  
                    type: 'value', 
                    splitArea: {show: true}  
                }  
            ],  
            series: [  
                {  
                    name: barName,    
                    type: chartType,
                    itemStyle: {
                        normal: {
                            color:chartColor
                        }
                    }, 
                    data: data2,
                    label: {
                        normal: {
                            show: true,
                            position: 'right',
                            textStyle:{
                                color:"#ffffff"
                            }
                        }
                    }
                }
            ]  
        };
        ec2.setOption(option_second);
    };

    //饼图
    var chart3 = function(id,data1,data2,chartType,barName,legend_posi,pie_posi,pie_color){
        var ec3 = module.exports.ec3 = echarts.init(document.getElementById(id),'dark');  

        var l_posi = legend_posi || 'left';
        var p_posi = pie_posi || ['55%', '46%'];
        var pie_data = [];
        $.each(data1,function(i,e){
            pie_data.push({name:e,value:data2[i]})
        });
        var option_second = {
            tooltip : {
                trigger: 'item',
                formatter: "{a} <br/>{b}  <br/>{c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                //left: l_posi,
                right:"2%",
                data: data1,
                bottom:"5%",
                selectedMode:false
            }, 
            color:pie_color,
            series: [  
                {  
                    name: barName,    
                    type: chartType,
                    radius: '66%',
                    center: p_posi,
                    data: pie_data,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        },
                        normal:{ 
                            label:{ 
                                show: true, 
                                formatter: '{d}%' 
                            }, 
                            labelLine :{show:true} 
                        }
                    }
                }
            ]  
        };
        ec3.setOption(option_second);
    };

    

    //堆叠折线图
    var chart4 = function(id,data1,data2,chartType,barName){
        var ec4  = module.exports.ec4 = echarts.init(document.getElementById(id),'dark'); 
        var cate_data = [],
            all_data = [];
        $.each(data2,function(i,e){
            cate_data.push(e.name);
            e.type = 'line';
            e.color = [e.color];
            e.smooth = true;
            //e.stack = barName;
            all_data.push(e);
        });
        var option_second = {
            /*title: {
                text: '折线图堆叠'
            },*/
            tooltip: {
                trigger: 'axis',
                axisPointer : {
                    type : 'shadow'
                }
            },
            legend: {
                data:cate_data
            },
            grid: {  
                left: '3',  
                right: '20',  
                bottom: '0',  
                top:'80',
                containLabel: true  
            },
            xAxis: {
                type: 'category',
                //boundaryGap: false,
                data: data1
            },
            yAxis: {
                type: 'value'
            },
            series: all_data
        };
        ec4.setOption(option_second);
    };
    //仪表盘
    var chart5 = function(id,data_value,name){
        var ec5 = module.exports.ec5 = echarts.init(document.getElementById(id),'dark');  

        var option = {
            tooltip : {
                show:false
                //formatter: "{a}:<br/> {c}%"
            },
            series: [
                {
                    name: name,
                    type: 'gauge',
                    detail: {formatter:'{value}%'},
                    radius:'90%',
                    axisLabel: {
                        show: false
                    },
                    axisLine: {
                        lineStyle: {  
                            width: 10,
                            color: [[0.2, '#1aa08b'], [0.8, '#086eb9'], [1, '#e5504b']]
                        }
                    },
                    axisTick:{
                        show:false
                    },
                    splitLine:{
                        length:5
                    },
                    pointer:{
                        width:5
                    },
                    title:{
                        offsetCenter:[0, '95%'],
                        color:'#ffffff',
                        fontSize:15

                    },
                    detail:{
                        offsetCenter:[0, '60%'],
                        color:'#ffffff',
                        fontSize:15,
                        formatter: function (value) {
                            return value + '%';
                        }
                    },
                    data: [{value:data_value,name:name}]
                }
            ]
        };
        ec5.setOption(option);
    };

    // 柱状图
    var chart6 = function(id,data1,data2,color1,color2){
        var ec6 = module.exports.ec6 = echarts.init(document.getElementById(id),'dark');  

        var option = {
            tooltip : {
                trigger: 'axis',
                axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                    type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            legend: {
                data:data1
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis : [
                {
                    type : 'category',
                    data : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    name:data1[0],
                    type:'bar',
                    barWidth: '10%',
                    itemStyle: {
                        normal: {
                            color:color1
                        }
                    }, 
                    data:[data2[0]]
                },
                {
                    name:data1[1],
                    type:'bar',
                    stack: '广告',
                    barWidth: '10%',
                    itemStyle: {
                        normal: {
                            color:color2
                        }
                    }, 
                    data:[data2[1]]
                }
            ]
        };
        ec6.setOption(option);
    };

    var chart7 = function(id,data1,data2,color_array){
        var ec7 = module.exports.ec7= echarts.init(document.getElementById(id),'dark'); 

        var legend_data = [],
            series_data = [];
        $.each(data2,function(i,e){
            legend_data.push(e.name)
            series_data.push({name:e.name,type:'bar',barMaxWidth:30,data:e.data})
        });

        if(data1.length >10 ){  
            var dataZoom_end = 100-(30/data1.length)*100;  
        }else{  
            var dataZoom_end = 0;  
        };

        var labelOption = {
            normal: {
                rotate: 90,
                align: 'left',
                verticalAlign: 'middle',
                position: 'insideBottom',
                distance: 15
            }
        };

        var option_second = {
            color: color_array,
            tooltip : {
                trigger: 'axis',
                axisPointer : {
                    type : 'shadow'
                }
            },
            legend: {
                y:'top',
                data: legend_data
            },
            grid: {  
                left: '3',  
                right: '20',  
                bottom: '25',  
                top:'30',
                containLabel: true  
            },
            calculable: true,
            dataZoom:[{
                height:'20',
                start:0,
                end:dataZoom_end,
                type:'slider', 
                bottom:0,
                textStyle:{
                    color:'#fff',
                    fontSize:'0'
                }
            }
          ],
            xAxis: [
                {
                    type: 'category',
                    axisTick: {show: false},
                    data: data1
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: series_data
        };
        ec7.setOption(option_second);
    };

    //柱状图与折线图混和
    var chart8 = function(id,data1,data2,color_array){
        var ec8 = module.exports.ec8= echarts.init(document.getElementById(id),'dark'); 

        var legend_data = [],
            series_data = [];
        $.each(data2,function(i,e){
            legend_data.push(e.name)
            series_data.push({name:e.name,type:e.type,barMaxWidth:30,data:e.data})
        });

        if(data1.length >10 ){  
            var dataZoom_end = 100-(9/data1.length)*100;  
        }else{  
            var dataZoom_end = 0;  
        };

        var labelOption = {
            normal: {
                rotate: 90,
                align: 'left',
                verticalAlign: 'middle',
                position: 'insideBottom',
                distance: 15
            }
        };

        var option_second = {
            color: color_array,
            tooltip : {
                trigger: 'axis',
                axisPointer : {
                    type : 'shadow'
                }
            },
            legend: {
                y:'top',
                data: legend_data
            },
            grid: {  
                left: '3',  
                right: '20',  
                bottom: '20',  
                top:'30',
                containLabel: true  
            },
            calculable: true,
            dataZoom:[{
                height:'14',
                start:0,
                end:dataZoom_end,
                type:'slider', 
                bottom:0,
                textStyle:{
                    color:'#fff',
                    fontSize:'0'
                }
            }
          ],
            xAxis: [
                {
                    type: 'category',
                    axisTick: {show: false},
                    data: data1
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: series_data
        };
        ec8.setOption(option_second);
    };


    formatNum = function(str){
        var newStr = "";
        var count = 0;
 
        if(str.indexOf(".")==-1){
            for(var i=str.length-1;i>=0;i--){
                if(count % 3 == 0 && count != 0){
                    newStr = str.charAt(i) + "," + newStr;
                }else{
                    newStr = str.charAt(i) + newStr;
                }
                count++;
            }
            str = newStr;// + ".00"; //自动补小数点后两位
        }else{
            for(var i = str.indexOf(".")-1;i>=0;i--){
                if(count % 3 == 0 && count != 0){
                    newStr = str.charAt(i) + "," + newStr;
                }else{
                    newStr = str.charAt(i) + newStr; //逐个字符相接起来
                }
                count++;
            }
            str = newStr + (str + "00").substr((str + "00").indexOf("."),3);
        }
        return str;
    };
    digital_num = function(name){
        $('.'+name).each(function(){
            var num_dom = $(this);
            var number = num_dom.html();
            num_dom.html(formatNum(number))
        });
    }

    loading_finished = function(){
        //去掉loading
        $('body').addClass('bigData');
    }


    /*
    * 输出
    */
    module.exports = {
        layoutSet:function(callback){
            $('.dPart').each(function(i,e){
                var $this =  $(e),
                    all_height = $this.height(),
                    resize_box = $this.find('.resize'),
                    static_box = $this.find('.static'),
                    static_height = static_box.height(),
                    box_length = $this.find('.sbox').length,
                    border_length = $this.find('.border').length,
                    resize_length = resize_box.length;
                if(static_box.length < 1){
                    resize_height = (all_height-box_length*10-border_length*2)/resize_length;
                }else{
                    resize_height = (all_height-box_length*10-border_length*2-static_height)/resize_length;
                }
                resize_box.height(resize_height);
                var resize_box_hd = resize_box.find('.hd').outerHeight()+10;
                resize_box.find('.my_echarts').height(resize_height - resize_box_hd -10);
                //if (callback && typeof callback === 'function') callback();
                $('.static_content').each(function(){
                    var _this = $(this);
                    var _oth = $(this).siblings(),
                        oth_height = 0;
                    if(_oth.attr('class') != 'static_content'){
                        oth_height +=  _oth.outerHeight();
                    };
                    _this.height(_this.parents('.sbox').height() - oth_height);
                })
            });
        },
        chart1:chart1,
        chart2:chart2,
        chart3:chart3,
        chart4:chart4,
        chart5:chart5,
        chart6:chart6,
        chart7:chart7,
        chart8:chart8,
        formatNum:formatNum,
        digital_num:digital_num,
        loading_finished:loading_finished,
        api:{
            //人口月度曲线图
            'month_people':'/test/month_people.json',
            //街乡人口月度双柱图
            'place_people':'/test/place_people.json',
            //街乡流动人口月度柱形图
            'ldrk_mouth':'/test/ldrk_mouth.json',
            //人口结构
            'structure':'/test/structure.json',
            //人居状况
            'houseing_status':'/test/houseing_status.json',
            //预警
            'alerted':'/test/alerted.json',
            //分析预测
            'analysis':'/test/analysis.json',
            //分析预测详情
            'anialysis_detail':'/test/anialysis_detail.json',
            //朝阳区地图数据
            'chaoyangqu':'/test/chaoyangqu.json',
            //东风乡地图数据
            'dongfengxiang':'/test/dongfengxiang.json',
        }
    };

    /*
    * 站内公用
    */
 

    require('lib/vue');
    require('lib/axios');
    var qs = require('lib/qs');

    

    //全局配置
    axios.interceptors.request.use(function(config){
        //在请求发出之前进行一些操作
        if(config.method  === 'post'){
            config.data = qs.stringify(config.data);
        };
        return config;
    },function(error){
        // Do something with request error
        return Promise.reject(error);
    });

    axios.interceptors.response.use(function(response){
        return response;
    },function(error){
        alert('数据请求失败，请刷新页面重试！');
        //console.warn(error.response);
        return Promise.reject(error.response.data)
    });

    //设置输出主体内容高度
    var winH = $(window).height(),
        headH = $('.pageHeader').outerHeight();
        $('body').height(winH);
    var mainH = module.exports.mainH = winH - headH;
    $(window).resize(function(){
        var winH_r = $(window).height(),
            headH_r = $('.pageHeader').outerHeight();
        $('.pageMain,.dPart').height(winH_r - headH_r);
        $('body').height(winH);
    }).resize();

    $(window).resize(function(){
        document.location.reload()
    });

    require('select');
    $('.top_select').select({
        hideSelected:true,
        hook:'topSelect',
        callback: function(value,text) { 
            console.log('value值为:'+value+'；text值为:'+text);
            if(value == 0){
                map_recovery();
                return false;
            };
            //临时demo处理
            map_recovery();
            setTimeout(function(){
                show_area();
            },500);
        }
    });
  
  
})